const qs = require("querystring");

function getReqBody(req) {
    return new Promise((resolve, reject) => {
        let body = "";

        req.on("data", (buffer) => {
            body += buffer.toString();
        });

        req.on("end", () => {
            // kebab-case小写中划线 camel-case小驼峰 Pascal-case大驼峰
            switch (req.headers["content-type"]) {
                case "application/x-www-form-urlencoded":
                    resolve(qs.parse(body));
                    break;
                case "application/json":
                    resolve(JSON.parse(body));
                    break;

                default:
                    reject({ err: "请求体必须为form或json格式" });
                    break;
            }
            resolve();
        });
        
        req.on("error", (err) => {
            reject(err);
        });
    });
}

module.exports = {
    getReqBody,
};
